﻿using System;
using System.Linq;
using Enyim.Caching;
using System.Web.Mvc;
using Web.Components;
using SilenthinkContract;
using System.Threading.Tasks;
using SilenthinkContract.Domain;
using SilenthinkCommon.Extension;
using SilenthinkContract.Component;

namespace Web.Areas.Passport.Controllers
{
    public class RegisterController : PassportBaseController
    {
        private const string RegisterSessionKey = "register.session.key";


        public RegisterController(ILogService logService, IBaseService baseService, IExtraService extraService, IStoreService storeService, IOrderService orderService, IGameService gameService, IAuctionService auctionService, IPassportService passportService, IPaymentService paymentService, IMemcachedClient memcachedClient) : base(logService, baseService, extraService, storeService, orderService, gameService, auctionService, passportService, paymentService, memcachedClient)
        {
        }

        public ActionResult Index(string code)
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string username, string password, string captcha, string code)
        {
            var id = Guid.NewGuid();
            var result = new SkResult<string>();
            if (!username.IsEmail() || password.IsNullOrEmpty())
            {
                result.Message = "用户名或密码不符合规范，请重新输入。";
                return Json(result);
            }
            if (!ValidateCaptcha(RegisterSessionKey, captcha))
            {
                result.Message = "请输入正确的验证码！";
                return Json(result);
            }
            var exist = PassportService.ExistUserName(username);
            if (!exist)
            {
                var log = new RegisterLog();
                log.Id = id;
                log.Origin = 1;
                log.UserName = username;
                log.Password = (password.ToPassword() + PasswordSalt).ToPassword();
                log.UserAgent = GetUserAgent();
                log.Browser = GetBrowser();
                log.IpAddress = GetIpAddress();
                log.UrlReferrer = GetUrlReferrer();
                log.CreatedOn = DateTime.Now;
                log.TraceCode = code;
                RegisterLog(log);
                result.Status = true;
                result.Message = id.ToString();
            }
            else
            {
                result.Message = "帐号已存在。";
            }
            return Json(result);
        }

        public ActionResult Validate(Guid? param)
        {
            var result = new SkResult<string>();
            if (param.HasValue)
            {
                var log = ExtraService.GetRegisterLog(param.Value);
                if (log == null)
                {
                    result.Message = "链接无效或已过期！";
                }
                else
                {
                    var exist = PassportService.ExistUserName(log.UserName);
                    if (!exist)
                    {
                        var user = new User();
                        user.Guid = log.Id.ToString();
                        user.Origin = log.Origin;
                        user.Name = log.UserName;
                        user.Password = log.Password;
                        user.Role = string.Empty;
                        user.NickName = string.Empty;
                        user.CreatedOn = log.CreatedOn;

                        var profile = new UserProfile();

                        var extra = new UserExtra();

                        user.UserProfile = profile;
                        user.UserExtra = extra;
                        result.Status = PassportService.CreateUser(user);
                    }
                    else
                    {
                        result.Message = "该帐号已激活！";
                    }
                }
            }
            else
            {
                result.Message = "参数不正确！";
            }
            return View(result);
        }

        public ActionResult Captcha()
        {
            return Captcha(RegisterSessionKey);
        }
        [HttpPost]
        public ActionResult ByMobile(string mobile, string password, string smscode, string code)
        {
            var result = new SkResult<string>();
            if (!mobile.IsMobile() || password.IsNullOrEmpty())
            {
                result.Message = "用户名或密码不符合规范，请重新输入！";
                return Json(result);
            }
            var log = ExtraService.GetSmsVerification(smscode, mobile, 0);
            if (log == null || mobile != log.Mobile)
            {
                result.Message = "短信验证码不正确或已过期！";
                return Json(result);
            }
            var exist = PassportService.ExistUserName(mobile);
            if (!exist)
            {
                var user = new User();
                user.Guid = log.Id.ToString();
                user.Origin = 2;
                user.Name = mobile;
                user.Password = (password.ToPassword() + PasswordSalt).ToPassword();
                user.Role = string.Empty;
                user.Level = 0;
                user.Email = null;
                user.NickName = null;
                user.Mobile = mobile;
                user.Status = UserStatus.Normal;
                user.LastLoginTime = DateTime.Now;
                user.LastIpAddress = GetIpAddress();
                user.CreatedOn = log.CreatedOn;

                var profile = new UserProfile();

                var extra = new UserExtra();

                user.UserProfile = profile;
                user.UserExtra = extra;
                result.Status = PassportService.CreateUser(user);
            }
            else
            {
                result.Message = "该手机号码已被使用，请换一个！";
            }
            return Json(result);
        }

        [HttpPost]
        public ActionResult ReSend(Guid? param)
        {
            if (!param.HasValue)
            {
                return HttpNotFound();
            }
            var id = Guid.NewGuid();
            var result = new SkResult<string>();
            var o = ExtraService.GetRegisterLog(param.Value);
            var log = new RegisterLog();
            log.Id = id;
            log.Origin = 1;
            log.UserName = o.UserName;
            log.Password = o.Password;
            log.UserAgent = GetUserAgent();
            log.Browser = GetBrowser();
            log.IpAddress = GetIpAddress();
            log.UrlReferrer = GetUrlReferrer();
            log.CreatedOn = DateTime.Now;
            RegisterLog(log);

            result.Status = true;
            result.Message = id.ToString();
            return Json(result);

        }
        public JsonResult CheckName(string username)
        {
            var status = !PassportService.ExistUserName(username);
            return Json(status, JsonRequestBehavior.AllowGet);
        }
        public JsonResult CheckCaptcha(int param, string captcha)
        {
            var status = ValidateCaptcha(RegisterSessionKey, captcha);
            return Json(status, JsonRequestBehavior.AllowGet);
        }
         public JsonResult CheckSmsCode(string mobile, string smscode)
         {
             var status = ExtraService.GetSmsVerification(smscode, mobile, 0);
            return Json(status!=null, JsonRequestBehavior.AllowGet);
        }

        private void RegisterLog(RegisterLog log)
        {
            var url = string.Format("http://passport.silenthink.com/register/validate/{0}", log.Id);
            Task.Factory.StartNew(() => Register(log, new { Url = url }));
        }
    }
}
